package com.hhm.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hhm.pojo.User;
import com.hhm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

/**
 * 用户登录
 */
@RequestMapping("user")
@Controller
public class UserController {
    @Autowired
    private UserService us;

    @RequestMapping("auth")
    public Object auth(String code,HttpServletResponse response){
        //获取access_token 钥匙
        //POST请求
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("client_id", "d654ea837584773a145e0637d142f691a77f8617a78891f32e2dd80cc7b70aed");
        paramMap.put("redirect_uri", "http://localhost:80/user/auth");
        paramMap.put("client_secret", "f502c51635d66119738a9b27a8f71f9fa16c2cfa7a1a48544224a6f8f557bee8");
        //url
        String url = "https://gitee.com/oauth/token";
        //token --- json格式
        String token = HttpUtil.post(url, paramMap);
        //解析
        JSONObject jsonObject = JSON.parseObject(token);
        //获取access_token
        Object access_token = jsonObject.get("access_token");

        //获取用户名
        //get请求获取授权用户的资料   返回json字符串
        String json = HttpUtil.get("https://gitee.com/api/v5/user?access_token=" + access_token);
        //解析
        JSONObject jsonObject1 = JSON.parseObject(json);
        //获取用户名
        Object username = jsonObject1.get("name");

        //判断第三方用户是否在数据库存在
        User user = us.getUser(username.toString());
        //不存在--创建
        if (user==null){
            user=new User();
            user.setUsername(username.toString());
            us.add(user);
        }
        //生成用户token
        String tokenOfUser = JWT.create()
                .setPayload("username", username)
                .setPayload("uid", user.getUid())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(), DateField.HOUR,12))
                .sign();
        //将token写到浏览器
        Cookie cookie = new Cookie("login_token", tokenOfUser);
        cookie.setPath("/");
        response.addCookie(cookie);
        //跳转页面
        return "redirect:/mains/list";

    }

    /**
     * 普通登录
     * @return
     */
    // 密钥
    byte[] key = "1234567890".getBytes();
    @RequestMapping("login")
    public String login(String username, String password, Model model, HttpServletResponse response){
        //账号、密码非空
        if (StringUtils.isEmpty(username)){
            model.addAttribute("error", "账号为空");
            return "login";
        }
        if (StringUtils.isEmpty(password)){
            model.addAttribute("error", "密码为空");
            return "login";
        }
        //都存在--查询数据库  判断账号和密码
        User userDB = us.getUser(username);
        if (userDB==null){
            model.addAttribute("error", "账户不存在");
            return "login";
        }
        //用户密码
        String pwd = DigestUtils.md5DigestAsHex((password + userDB.getSalt()).getBytes());
        if (!pwd.equals(userDB.getPassword())){
            model.addAttribute("error", "密码错误");
            return "login";
        }

        //都正确--生成令牌
        String token = JWT.create()
                .setPayload("username", username)
                .setPayload("uid", userDB.getUid())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(), DateField.HOUR,12))
                .sign();
        //将token写到浏览器
        Cookie cookie = new Cookie("login_token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        //跳转页面
        return "redirect:/mains/list";
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }
}
